//
//  ZFWeatherView.swift
//  map
//
//  Created by fyzq on 2024/1/31.
//

import UIKit

class ZFWeatherView: ZFBaseView {

    private var weatherIconLabel :UILabel!
    private var tempLabel :UILabel!
    private var textLabel :UILabel!
    override init(frame: CGRect) {
        super.init(frame: frame)
        setZFWeatherView()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    fileprivate func setZFWeatherView(){
        weatherIconLabel = UILabel()
        weatherIconLabel.font = UIFont.weatherfont(size:20)
        weatherIconLabel.textColor = R.color.accentColor()
        addSubview(weatherIconLabel)
        weatherIconLabel.snp.makeConstraints { make in
            make.left.equalTo(5)
            make.centerY.equalToSuperview()
        }

        tempLabel = UILabel()
        tempLabel.font = UIFont.systemFont(ofSize: 10)
        tempLabel.textColor = R.color.color_66()

        textLabel = UILabel()
        textLabel.font = UIFont.systemFont(ofSize: 10)
        textLabel.textColor = R.color.color_33()

        let stackView =  UIStackView(arrangedSubviews: [tempLabel,textLabel])
        stackView.axis = .vertical
        stackView.alignment = .fill
        stackView.spacing = 3
        stackView.distribution = .fillEqually
        addSubview(stackView)
        stackView.snp.makeConstraints { make in
            make.left.equalTo(weatherIconLabel.snp.right).offset(10)
            make.top.equalTo(3)
            make.bottom.equalTo(-3)
            make.right.equalTo(-10)
        }
        
        backgroundColor = R.color.bg()
        addRadius(radius: 5)
    }

    
    
}

extension ZFWeatherView {
    
    func loadNowWeather(){
        ZFWeatherManager.getDayWeather().subscribe(onNext: {[weak self]weahter in
            guard let self = self else {return}
            self.textLabel.text = weahter.text
            self.tempLabel.text = weahter.temp + "°C"

            do {
                let data = try Data(contentsOf: R.file.weatherJson()!)
                   // 将数据转换为字典或其他需要的格式
                if let jsonObject = try? (JSONSerialization.jsonObject(with: data) as! [String : Any]) {
//                       print("JSON Object:\n\(jsonObject)")
                    guard let ad = Unicode.Scalar(jsonObject[weahter.icon] as! Int) else {
                        return
                    }
                    self.weatherIconLabel.text = String(ad)
                   } else {
                       print("无法解析 JSON 数据")
                   }
               } catch {
                   print("发生错误：\(error)")
               }
        }).disposed(by: dis)
        
    }
}
